package service;

import common.Message;
import common.MessageType;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 文件传输服务
 * @author 余一
 * @date 2021/10/31  16:56
 */
public class FileService {

    /**
     * 发送一个文件
     * @param src
     * @param destination
     * @param sender
     * @param receiver
     */
    public void sendOne(String src,String destination,String sender,String receiver){
        Message message = new Message();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
        String nowTime = formatter.format(now);
        message.setSendTime(nowTime);
        message.setSender(sender);
        message.setMesType(MessageType.MESSAGE_FILE_MES);
        message.setGetter(receiver);
        message.setTarget(destination);
        message.setSrc(src);

        //根据路径读取磁盘文件
        FileInputStream fileInputStream = null;
        byte[] fileBytes = new byte[(int) new File(src).length()];
        try {
            fileInputStream = new FileInputStream(src);
            fileInputStream.read(fileBytes);
            message.setFileBytes(fileBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //提示信息
        System.out.println("\n【" + sender + "】给【" + receiver + "】发送文件：" + src + "到对方目录：" + destination);

        //将message发送给服务端
        try {
            OutputStream outputStream = ThreadManager.getThread(sender).getSocket().getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
